﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using Segmentation.Business.Criterions;

namespace Segmentation.Business
{
    public class ModelImage : ImageContainer
    {
        #region Fields

        private Bitmap bitmap;
        private byte[,] map;
        private CriterionCollection criterions;

        #endregion

        #region Constructors

        private ModelImage(Bitmap bitmap, byte[,] map)
            : base(bitmap)
        {
            this.map = map;
            this.criterions = new CriterionCollection();
        }

        #endregion

        #region Properties

        public byte[,] Map
        {
            get
            {
                return this.map;
            }
        }

        public CriterionCollection Criterions
        {
            get
            {
                return this.criterions;
            }
        }

        #endregion

        #region Methods

        public CriterionCollection CalculateCriterions()
        {
            this.criterions.Calculate(this.map, base.JSEGAccessor.RegionMap);
            return this.criterions;
        }

        #endregion Methods

        #region Static Methods

        public static ModelImage Create(int width, int height, Color color1, Color color2)
        {
            Bitmap bitmap = new Bitmap(width, height);
            byte[,] map = new byte[height, width];

            Rectangle rect1 = new Rectangle(0, 0, width / 2, height);
            Rectangle rect2 = new Rectangle(width / 2, 0, width - (width / 2), height);

            Graphics drawGraphics = Graphics.FromImage(bitmap);
            Brush brush1 = new SolidBrush(color1);
            Brush brush2 = new SolidBrush(color2);

            drawGraphics.FillRectangle(brush1, rect1);
            drawGraphics.FillRectangle(brush2, rect2);

            brush1.Dispose();
            brush2.Dispose();
            drawGraphics.Dispose();

            FillMap(map, rect1, 0);
            FillMap(map, rect2, 1);

            ModelImage modelImage = new ModelImage(bitmap, map);
            return modelImage;
        }

        private static void FillMap(byte[,] map, Rectangle rect, byte value)
        {
            for (int y = rect.Top; y < rect.Bottom; y++)
            {
                for (int x = rect.Left; x < rect.Right; x++)
                {
                    map[y, x] = value;
                }
            }
        }

        #endregion
    }
}
